package com.example.demo.datasources.aspect;


import com.example.demo.datasources.DataSourceNames;
import com.example.demo.datasources.DynamicDataSourceContextHolder;
import com.example.demo.datasources.annotation.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源，切面处理类
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect implements Ordered {
    @Pointcut("@annotation(com.example.demo.datasources.annotation.DataSource)")
    public void dataSourcePointCut() {

    }


    @Around("dataSourcePointCut()")
    public Object before(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        if (ds == null || !DynamicDataSourceContextHolder.isContainsDataSource(ds.name())) {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceNames.MASTER);
            log.info("set datasource is " + DataSourceNames.MASTER);
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(ds.name());
            log.info("set datasource is " + ds.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }


    @Override
    public int getOrder() {
        return 1;
    }

}
